************************************************
*** BUILD DATASET ON RURAL HOSPITAL CLOSURES ***
*** AND EXPLORATORY ANALYSIS 				 ***
*** Last edited: 5/3/21         		   	 ***
************************************************

log using "${CodePath}/log/build_hospclosure_$S_DATE.log", text replace

// Clean Sheps data on rural hospital closures -- https://www.shepscenter.unc.edu/programs-projects/rural-health/rural-hospital-closures/ (downloaded on 3/1/2022)
import excel "${DataPath}/hospital-closures/Closures-Database-for-Web.xlsx", firstrow clear 
keep if !missing(pn) // keep only the ones that also show up in the HCRIS data

// consolidate the repeats by using the last year as the closure year for that pn
bys pn: egen closure_year2 = max(closure_year)
drop closure_year
rename closure_year2 closure_year
keep pn closure_year
duplicates drop
save "${DataPath}/hospital-closures/sheps_hospclosures.dta", replace

// match Sheps data with the panel data
	use "${DataPath}/derived/hospyear_0716_jk.dta", clear
	tsset pn fyear
	drop if missing(pn) | missing(fyear)
	tsfill, full

	preserve
		use "${DataPath}/hospital-closures/sheps_hospclosures.dta", clear
		tempfile temp
		save `temp'
	restore

	merge m:1 pn using `temp', gen(_hospclosure_m) keep(1 3)


	bys pn: egen hospclosure = max(_hospclosure_m) 
	replace hospclosure = 0 if hospclosure == 1
	replace hospclosure = 0 if hospclosure == 3 & fyear < closure_year
	replace hospclosure = 1 if hospclosure == 3 & fyear >= closure_year

	bys pn: egen ever_close = max(_hospclosure_m) 
	replace ever_close = 0 if ever_close == 1
	replace ever_close = 1 if ever_close == 3

	drop _hospclosure_m

	keep ever_close hospclosure closure_year urgeo pn fyear hosp_name state dist_to_border RACregion_audit* jk_RACregion_audit_in2011* jk_state_audit_in2011* state_audit_in2011* audit_in2011* jk_RACregion_audit_in2011* demandrate_in2011* jk_RACregion_demand_in2011*  jk_state_demand_in2011* nearseg100_state_2 nearseg100_state RACregion state 
	save "${DataPath}/hospital-closures/hospyear_0716_jk_hospclosure.dta", replace


log close
